// 背景脚本 - 处理扩展事件和维护状态

// 扩展安装或更新时的处理
chrome.runtime.onInstalled.addListener(function(details) {
  if (details.reason === "install") {
    console.log("扩展已安装");
    
    // 初始化存储数据
    initializeStorage();
  } else if (details.reason === "update") {
    console.log("扩展已更新到版本 " + chrome.runtime.getManifest().version);
    
    // 检查并更新存储结构
    updateStorageIfNeeded();
  }
});

// 初始化存储数据
function initializeStorage() {
  chrome.storage.sync.get(['credentials'], function(result) {
    if (!result.credentials) {
      // 设置初始示例数据
      const initialData = {
        credentials: [
          {
            id: '1',
            username: 'admin',
            password: 'admin123',
            region: '测试环境-CN',
            note: '测试账号'
          },
          {
            id: '2',
            username: 'test01',
            password: 'test123',
            region: '测试环境-CN',
            note: '测试人员账号'
          },
          {
            id: '3',
            username: 'admin',
            password: 'adminUS123',
            region: '测试环境-US',
            note: '美国测试环境'
          },
          {
            id: '4',
            username: 'admin',
            password: 'prod!123',
            region: '生产环境-CN',
            note: '生产账号，谨慎使用'
          }
        ]
      };
      
      chrome.storage.sync.set(initialData, function() {
      });
    }
  });
}

// 检查并更新存储结构
function updateStorageIfNeeded() {
  chrome.storage.sync.get(['credentials'], function(result) {
    if (result.credentials) {
      // 检查所有凭据是否有id字段，如果没有则添加
      let updated = false;
      result.credentials.forEach((credential, index) => {
        if (!credential.id) {
          credential.id = Date.now().toString(36) + index;
          updated = true;
        }
      });
      
      if (updated) {
        chrome.storage.sync.set({credentials: result.credentials}, function() {
        });
      }
    }
  });
}

// 监听来自内容脚本或弹出窗口的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === "getCredentials") {
    // 获取所有凭据
    chrome.storage.sync.get(['credentials'], function(result) {
      sendResponse({credentials: result.credentials || []});
    });
    return true; // 表示异步响应
  }
  
  if (request.action === "saveCredential") {
    // 保存或更新凭据
    saveCredential(request.credential, sendResponse);
    return true;
  }
  
  if (request.action === "deleteCredential") {
    // 删除凭据
    deleteCredential(request.id, sendResponse);
    return true;
  }
});

// 保存或更新凭据
function saveCredential(credential, callback) {
  chrome.storage.sync.get(['credentials'], function(result) {
    const credentials = result.credentials || [];
    
    // 检查是否存在相同ID的凭据
    const index = credentials.findIndex(c => c.id === credential.id);
    
    if (index >= 0) {
      // 更新现有凭据
      credentials[index] = credential;
    } else {
      // 添加新凭据
      if (!credential.id) {
        credential.id = Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
      }
      credentials.push(credential);
    }
    
    chrome.storage.sync.set({credentials: credentials}, function() {
      if (callback) callback({success: true});
    });
  });
}

// 删除凭据
function deleteCredential(id, callback) {
  chrome.storage.sync.get(['credentials'], function(result) {
    let credentials = result.credentials || [];
    
    // 过滤掉要删除的凭据
    credentials = credentials.filter(c => c.id !== id);
    
    chrome.storage.sync.set({credentials: credentials}, function() {
      if (callback) callback({success: true});
    });
  });
}

// 设置图标右键菜单
chrome.runtime.onInstalled.addListener(function() {
  chrome.contextMenus.create({
    id: "openPasswordManager",
    title: "打开密码管理器",
    contexts: ["browser_action"]
  });
});

// 监听右键菜单点击
chrome.contextMenus.onClicked.addListener(function(info, tab) {
  if (info.menuItemId === "openPasswordManager") {
    chrome.action.openPopup();
  }
}); 